package org.example.servlet;

import org.example.entity.SearchResult;
import org.example.service.UContentService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {
    private final UContentService uContentService = new UContentService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String query = req.getParameter("query");
            String type = req.getParameter("type");
            int page = getIntParameter(req, "page", 1);
            int limit = getIntParameter(req, "limit", 10);
            int offset = (page - 1) * limit;

            if (query == null || query.trim().isEmpty()) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "搜索关键词不能为空");
                return;
            }

            List<SearchResult> results = uContentService.searchContent(query, type, limit, offset);
            int totalCount = uContentService.getSearchCount(query, type);
            int totalPages = (int) Math.ceil((double) totalCount / limit);

            // 设置请求属性，用于JSP页面渲染
            req.setAttribute("searchResults", results);
            req.setAttribute("totalResults", totalCount);
            req.setAttribute("totalPages", totalPages);
            req.setAttribute("currentPage", page);

            // 转发到JSP页面
            req.getRequestDispatcher("/searchResults.jsp").forward(req, resp);

        } catch (SQLException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "搜索失败: " + e.getMessage());
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误: " + e.getMessage());
        }
    }

    private int getIntParameter(HttpServletRequest req, String name, int defaultValue) {
        String value = req.getParameter(name);
        if (value == null || value.isEmpty()) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
}